using System;
using System.ComponentModel;
using System.IO;
using System.Windows.Forms;
using RollManager.Library.Dialogs;
using RollManager.Library.Utils;

namespace RollManager.Library.ActionSteps
{
    [Serializable]
    public class ChooseFolderStep : ActionStep
    {
        private string m_srcDir = StepConstants.PATH;
        private string m_paramName = StepConstants.NAME;

        [DisplayName( "Parameter Name" )]
        [Description( "The name of the parameter to save for the steps in the script.  This will save the path to the folder chosen so it can be used by subsequent steps." )]
        public string ParamName
        {
            get
            {
                return m_paramName;
            }
            set
            {
                if( string.IsNullOrEmpty( value ) )
                {
                    throw new ArgumentException( "Parameter Name cannot be empty." );
                }
                else
                {
                    m_paramName = value.Trim();
                }
            }
        }

        [DisplayName( "Source Dir" )]
        [Description( "The source directory path from which a sub-folder is selected." )]
        public string SrcDir
        {
            get
            {
                return m_srcDir;
            }
            set
            {
                if( string.IsNullOrEmpty( value ) )
                {
                    throw new ArgumentException( "Source Dir cannot be empty." );
                }
                else
                {
                    m_srcDir = value.Trim();
                }
            }
        }

        public override string Name
        {
            get { return "Choose Folder"; }
        }

        protected override void Run()
        {
            selectFolder();
        }

        protected override void Simulate()
        {
            // Check for source dir
            DirectoryInfo dir = new DirectoryInfo( m_srcDir );
            if( !dir.Exists )
            {
                throw new Exception( string.Format( "Source dir {0} does not exist.", m_srcDir ) );
            }

            selectFolder();
        }

        private void selectFolder()
        {
            // Create and show dialog to choose sub-folder.
            ChooseFolderDialog dialog = new ChooseFolderDialog( 
                Common.ListDirectories( m_srcDir, "*.*", SearchOption.TopDirectoryOnly ) );
            DialogResult result = dialog.ShowDialog();

            if( result == DialogResult.OK )
            {
                Progress.AddFormat( "Folder selected: {0}", dialog.SelectedFolder );
                Context.Add( m_paramName, dialog.SelectedFolder );                
            }
            else
            {
                throw new Exception( "User cancelled folder selection." );
            }
        }
    }
}
